package cn.zero.letaomallspringboot.common;

public class IdGenerator {

    // 起始时间戳：2025-01-01 00:00:00
    private static final long START_TIMESTAMP = 1735689600000L;

    // 序列号位数（每毫秒支持 1024 个 ID）
    private static final long SEQUENCE_BITS = 10L;
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS); // 1023

    private static long lastTimestamp = -1L;
    private static long sequence = 0L;

    /**
     * 生成 10 位纯数字 ID（从 800000000 开始，永远不会重复）
     */
    public static synchronized Long nextId() {
        long current = System.currentTimeMillis();

        if (current < lastTimestamp) {
            throw new RuntimeException("时钟回拨，无法生成ID");
        }

        if (current == lastTimestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) {
                // 当前毫秒已用完，等待下一毫秒
                current = waitNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = current;

        // 生成原始雪花ID（41位时间戳 + 10位序列号 ≈ 51位）
        long id = (current - START_TIMESTAMP) << 10 | sequence;

        // 映射到 800_000_000 ~ 999_999_999 这个区间（10亿以内，int 安全）
        long finalId = 800000000L + (id % 200000000L);

        return finalId;
    }

    private static long waitNextMillis(long last) {
        long current = System.currentTimeMillis();
        while (current <= last) {
            current = System.currentTimeMillis();
        }
        return current;
    }
}